package com.edu.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.PutObjectResult;
import com.edu.eduservicebase.exception.GuliException;
import com.edu.oss.service.FileService;
import com.edu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {
        //获取阿里云存储相关常量
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        String uploadUrl = null;
        //
        try {
            OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
            if (!ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取文件上传
            InputStream inputStream = file.getInputStream();

            String filename = file.getOriginalFilename();
            //截取后缀得到文件名字
            filename= filename.substring(filename.lastIndexOf(".") + 1);

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
        // 8f8fd314484e4ead8c6e01efcf5e3a97/java校招.png
            filename=uuid+"/"+filename;

            String date = new DateTime().toString("yyyy/MM/dd");
            //2021/05/30/8f8fd314484e4ead8c6e01efcf5e3a97/java校招.png
            filename = date +"/"+filename;

            //文件上传至阿里云
            ossClient.putObject(bucketName, filename, inputStream);
            ossClient.shutdown();

            //获取url
            uploadUrl = "https://"+bucketName+"."+endPoint+"/"+filename;
        } catch (IOException e) {
           throw new GuliException();
        }

        return uploadUrl;
    }
}
